package org.easley.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.easley.pay.common.UserDto;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Callable;

/**
 * description
 *
 * @author zengwch
 * @date 2019年12月06日 23:02
 */
public class WeiboPayResultTask implements Callable<WeiboPayResult> {
    private String username;
    private String startTime;
    private String endTime;

    public WeiboPayResultTask(String username, String startTime, String endTime) {
        this.username = username;
        this.startTime = startTime;
        this.endTime = endTime;
    }


    @Override
    public WeiboPayResult call() {
        WeiboPayResult weiboPayResult =null;
        UserDto userDto =  WeiboPayViewUtil.USER_MAP.get(username);
        if(userDto !=null){
            try {
                long start =System.currentTimeMillis();
                String respJson = WeiboPayLogin.loginWithCookie("https://pay.sc.weibo.com/aj/pc/biz/list?biz_type=41&status=2&biz_id=&start_time=" + startTime + "&end_time="+ endTime + "&page=1&page_size=10000", userDto.getCookie());
                StringBuffer sb =new StringBuffer();
                sb.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                                .append("查询微博")
                                .append(username)
                                .append("耗时：")
                                .append(System.currentTimeMillis() -start )
                                .append("ms")
                                ;
                System.out.println(sb.toString());
                if (!StringUtils.isBlank(respJson)) {
                    weiboPayResult =new WeiboPayResult(username, getAmountFromJson(respJson));
                }else{
                    relogin(userDto);
                }
            } catch (Exception e) {
                StringBuffer sb =new StringBuffer();
                sb.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                                .append("查询微博")
                                .append(this.username)
                                .append("失败");
                System.out.println(sb.toString());
                relogin(userDto);
            }
        }
        return weiboPayResult;
    }

    private WeiboPayResult relogin(UserDto userDto){
        WeiboPayResult weiboPayResult =null;
        try{
            WeiboPayLogin weiboPayLogin = WeiboPayViewUtil.getWeiboPayLogin(username, userDto.getPassword());
            if (weiboPayLogin.getCookieSinaPassport() != null && StringUtils.isNotBlank(weiboPayLogin.getCookieSinaPassport().toString())) {
                userDto.setCookie(weiboPayLogin.getCookieSinaPassport().toString());
                WeiboPayViewUtil.addMap(userDto);
                String cookie = userDto.getCookie();
                String url = "https://pay.sc.weibo.com/aj/pc/biz/list?biz_type=41&status=2&biz_id"
                                + "=&start_time=" +startTime + "&end_time="+ endTime + "&page=1"
                                + "&page_size=5000";

                String respJson = WeiboPayLogin.loginWithCookie(url, cookie);
                if (!StringUtils.isBlank(respJson)) {
                    weiboPayResult =new WeiboPayResult(username, getAmountFromJson(respJson));
                }
            }else{
                WeiboPayViewUtil.delUser(username);
            }
        }catch (Exception e) {
            StringBuffer sb =new StringBuffer();
            sb.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                            .append("查询重新登录微博")
                            .append(this.username)
                            .append("失败");
            System.out.println(sb.toString());
        }
        return weiboPayResult;
    }

    private static String getAmountFromJson(String json) {
        JSONArray bizArr = JSON.parseObject(json).getJSONObject("data").getJSONArray("biz");
        long amountTotal = 0L;
        for (Object biz : bizArr) {
            JSONObject bizObj = JSON.parseObject(biz.toString());
            long bizAmount = yuan2Fen(bizObj.getString("amount"));
            if ("+".equals(bizObj.getString("amount_prefix"))) {
                amountTotal += bizAmount;
            }
            //            else {
            //                amountTotal -= bizAmount;
            //            }
        }
        return fen2Yuan(amountTotal);
    }

    private static Long yuan2Fen(String numStr) {
        BigDecimal decimal = new BigDecimal(numStr).setScale(2, RoundingMode.DOWN);
        return decimal.multiply(new BigDecimal("100")).longValue();
    }

    private static String fen2Yuan(long num) {
        return new BigDecimal(String.valueOf(num)).divide(new BigDecimal("100"), 2, RoundingMode.DOWN).toString();
    }
}
